package org.jhub1.system.xmpp.proxy;

import java.io.IOException;
import java.util.Iterator;

import org.jhub1.system.xmpp.commands.CommandExecutor;
import org.jhub1.system.xmpp.config.ConfigAdapter;
import org.jhub1.system.xmpp.gateway.packet.IQGatewayItems;
import org.jhub1.system.xmpp.log.LogAdapter;
import org.jivesoftware.smack.XMPPException;

public class IQProcessor {

	private static ConfigAdapter config;
	private static LogAdapter log = LogAdapter.getLog(IQProcessor.class);

	public IQProcessor(ConfigAdapter config) {
		IQProcessor.config = config;
	}

	public boolean process(IQGatewayItems gwi, String jidTo, String jidFrom)
			throws XMPPException, IOException {

		for (Iterator<IQGatewayItems.Item> iter = gwi.getWriteItems(); iter
				.hasNext();) {
			IQGatewayItems.Item item = (IQGatewayItems.Item) iter.next();
			if (item.getAccessType().equals("com")) {
				log.debug("COM - access type recognized.");
				/*
				 * COMMAND PROCESSING IN HERE
				 */
				CommandExecutor ce = new CommandExecutor(IQProcessor.config, "IQ");
				ProcessResponse pr = ce.executeComTask(item.getCommand(),
						item.getItems());
				if (pr.error) {
					item.setError(pr.errorMessage);
				} else {
					item.setText(pr.getMessageXMLSafe());
				}
				ce = null;
			} else if (item.getAccessType().equals("dir")) {
				log.debug("DIR - access type recognized.");
				/*
				 * DIRECT REQUEST PROCESSING IN HERE
				 */
				CommandExecutor ce = new CommandExecutor(IQProcessor.config, "IQ");
				ProcessResponse pr = ce.executeDirTask(item.getRequestType(),
						item.getUri(), item.getItems());
				if (pr.error) {
					item.setError(pr.errorMessage);
				} else {
					item.setText(pr.getMessageXMLSafe());
				}
			} else {
				item.setError("ACCESS_TYPE_UNKNOWN");
			}
		}

		XMPPProxy.sendIQ(jidTo, jidFrom, gwi);
		return false;
	}

}
